<html>
<head>
    <meta charset="utf-8" />
<meta name="description" content="" />
<meta name="viewport" content="width=device-width, initial-scale=1" />

<meta name="description" content="Alger的博客,这里有好多新奇的知识,以及一个小开发者的闲话">
<meta name="keywords" content="Alger,Alger的博客,alger,alger的博客,html,css,vue,刘俊杰的博客,刘俊杰,liujunjie,Alger开发,Android,刘先生">

<title> Android计算器案例🤖 | Alger&#39;s blog</title>

<link rel="shortcut icon" href="http://www.myalger.ml/favicon.ico?v=1598690869337">

<link href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" rel="stylesheet">
<link rel="stylesheet" href="http://www.myalger.ml/styles/main.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.0/dist/css/bootstrap.min.css">

<script src="https://cdn.jsdelivr.net/npm/@highlightjs/cdn-assets/highlight.min.js"></script>
<script src="https://cdn.bootcss.com/highlight.js/9.15.10/languages/dockerfile.min.js"></script>
<script src="https://cdn.bootcss.com/highlight.js/9.15.10/languages/dart.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/moment@2.27.0/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.0/dist/js/bootstrap.min.js"></script>
<!-- DEMO JS -->
<!--<script src="media/scripts/index.js"></script>-->


    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.12.0/dist/katex.css">
</head>
<body>
<div class="main gt-bg-theme-color-first">
    <nav class="navbar navbar-expand-lg">
    <div class="navbar-brand">
        <img class="user-avatar" src="/images/avatar.png" alt="头像">
        <div class="site-name gt-c-content-color-first">
            Alger&#39;s blog
        </div>
    </div>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <i class="fas fa-bars gt-c-content-color-first" style="font-size: 18px"></i>
    </button>
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <div class="navbar-nav mr-auto" style="text-align: center">
            
                <div class="nav-item">
                    
                        <a href="/" class="menu gt-a-link">
                            首页
                        </a>
                    
                </div>
            
                <div class="nav-item">
                    
                        <a href="/archives" class="menu gt-a-link">
                            归档
                        </a>
                    
                </div>
            
                <div class="nav-item">
                    
                        <a href="/tags" class="menu gt-a-link">
                            标签
                        </a>
                    
                </div>
            
                <div class="nav-item">
                    
                        <a href="http://www.myalger.ml/about" class="menu gt-a-link">
                            关于
                        </a>
                    
                </div>
            
        </div>
        <div style="text-align: center">
            <form id="gridea-search-form" style="position: relative" data-update="1598690869337" action="/search/index.html">
                <input class="search-input" autocomplete="off" spellcheck="false" name="q" placeholder="搜索文章" />
                <i class="fas fa-search gt-c-content-color-first" style="position: absolute; top: 9px; left: 10px;"></i>
            </form>
        </div>
    </div>
</nav>

    <div class="post-container">
        <div class="post-detail gt-bg-theme-color-second">
            <article class="gt-post-content">
                <h2 class="post-title">
                     Android计算器案例🤖
                </h2>
                <div class="post-info">
                    <time class="post-time gt-c-content-color-first">
                        · 2020-03-13 ·
                    </time>
                    
                        <a href="http://www.myalger.ml/uXar5IwUu/" class="post-tags">
                            # Android
                        </a>
                    
                </div>
                <div class="post-content">
                    <p>使用简单的网格布局管理器来实现界面🧨<br>
然后使用java代码来实现计算器的操作🎉</p>
<!-- more -->
<pre><code class="language-xml">//布局标签属性
android:orientation=&quot;horizontal&quot;    //设置水平方向排列
android:columnCount=&quot;4&quot;              //设置为四列
android:rowCount=&quot;8&quot;                  //设置为八行
//设置布局内组件属性
android:layout_rowWeight=&quot;2&quot;          //设置占两行
android:layout_columnSpan=&quot;4&quot;          //设置占四列
android:layout_gravity=&quot;bottom|right&quot;  //设置位置属性，如果设置前两行必须设置此属性才能使控件铺满
</code></pre>
<h3 id="布局部分代码">布局部分代码</h3>
<pre><code class="language-xml">//这里显示算式
&lt;TextView
    android:id=&quot;@+id/Results&quot;
    android:layout_rowWeight=&quot;2&quot;
    android:layout_columnSpan=&quot;4&quot;
    android:layout_gravity=&quot;bottom|right&quot;
    android:text=&quot;&quot;
    android:paddingEnd=&quot;15dp&quot;
    android:paddingStart=&quot;15dp&quot;
    android:textSize=&quot;40sp&quot; /&gt;
  
//这里显示结果
&lt;TextView
    android:id=&quot;@+id/viewResults&quot;
    android:layout_rowWeight=&quot;2&quot;
    android:layout_columnSpan=&quot;4&quot;
    android:layout_gravity=&quot;bottom|right&quot;
    android:text=&quot;0&quot;
    android:paddingEnd=&quot;15dp&quot;
    android:paddingStart=&quot;15dp&quot;
    android:textSize=&quot;40sp&quot; /&gt;
//这里是按钮，都一样复制改一下 id 和 text
&lt;Button
    android:id=&quot;@+id/btnClear&quot;
    android:layout_width=&quot;wrap_content&quot;
    android:layout_height=&quot;wrap_content&quot;
    android:layout_rowWeight=&quot;1&quot;
    android:layout_columnSpan=&quot;1&quot;
    android:layout_columnWeight=&quot;1&quot;
    android:layout_gravity=&quot;fill&quot;
    android:layout_margin=&quot;0.5dp&quot;
    android:background=&quot;#ffffff&quot;
    android:text=&quot;AC&quot;
    android:textColor=&quot;#f68904&quot;
    android:textSize=&quot;30sp&quot; /&gt;
</code></pre>
<figure data-type="image" tabindex="1"><img src="https://s1.ax1x.com/2020/03/13/8u9OZq.png" alt="8u9OZq.png" loading="lazy"></figure>
<h3 id="后台代码">后台代码</h3>
<pre><code class="language-java">//记得要使用 View.OnClickListener 接口不然不能实现点击事件
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    //声明对象
    private TextView Results;
    private TextView viewResults;
    private Button btn0;
    private Button btn1;
    private Button btn2;
    private Button btn3;
    private Button btn4;
    private Button btn5;
    private Button btn6;
    private Button btn7;
    private Button btn8;
    private Button btn9;
    private Button btnClear;
    private Button btnBackspace;
    private Button btnBai;
    private Button btnDian;
    private Button btnJia;
    private Button btnJian;
    private Button btnCheng;
    private Button btnChu;
    private Button btnResults;
     //声明一个 StringBuffer 用来存储输入的算式
    private StringBuffer str_display = new StringBuffer();



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //给变量复制，即找到对应的控件
        Results = findViewById(R.id.Results);
        viewResults = findViewById(R.id.viewResults);
        btn0 = findViewById(R.id.btn0);
        btn1 = findViewById(R.id.btn1);
        btn2 = findViewById(R.id.btn2);
        btn3 = findViewById(R.id.btn3);
        btn4 = findViewById(R.id.btn4);
        btn5 = findViewById(R.id.btn5);
        btn6 = findViewById(R.id.btn6);
        btn7 = findViewById(R.id.btn7);
        btn9 = findViewById(R.id.btn9);
        btn8 = findViewById(R.id.btn8);
        btnClear = findViewById(R.id.btnClear);
        btnBackspace = findViewById(R.id.btnBackspace);
        btnBai = findViewById(R.id.btnBai);
        btnDian = findViewById(R.id.btnDian);
        btnJia = findViewById(R.id.btnJia);
        btnJian = findViewById(R.id.btnJian);
        btnCheng = findViewById(R.id.btnCheng);
        btnChu = findViewById(R.id.btnChu);
        btnResults = findViewById(R.id.btnResults);
        //给按钮注册监听器
        btn0.setOnClickListener(this);
        btn1.setOnClickListener(this);
        btn2.setOnClickListener(this);
        btn3.setOnClickListener(this);
        btn4.setOnClickListener(this);
        btn5.setOnClickListener(this);
        btn6.setOnClickListener(this);
        btn7.setOnClickListener(this);
        btn8.setOnClickListener(this);
        btn9.setOnClickListener(this);
        btnClear.setOnClickListener(this);
        btnBackspace.setOnClickListener(this);
        btnBai.setOnClickListener(this);
        btnDian.setOnClickListener(this);
        btnJia.setOnClickListener(this);
        btnJian.setOnClickListener(this);
        btnCheng.setOnClickListener(this);
        btnChu.setOnClickListener(this);
        btnResults.setOnClickListener(this);
        

    }
//这是 View.OnClickListener 接口自带的方法
    @Override
    public void onClick(View v) {
        //用 switch 语句来判断点击了那个按钮
        switch (v.getId()){
            case R.id.btn0:
            case R.id.btn1:
            case R.id.btn2:
            case R.id.btn3:
            case R.id.btn4:
            case R.id.btn5:
            case R.id.btn6:
            case R.id.btn7:
            case R.id.btn8:
            case R.id.btn9:
            case R.id.btnDian:
            //在点击了数字和小数点时给 str_display 的 append 属性来向字符串后面添加数字或小数点，这样整个算式就会被 str_display 记录下来
                str_display.append(((Button)v).getText().toString());
                Results.setText(str_display);
                //在点击时可以实时的把运算结果显示出来，用到下面 calculate 的计算方法
                try {
                    viewResults.setText(&quot;=&quot;+calculate(str_display.toString()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.btnJia:
            case R.id.btnJian:
            case R.id.btnCheng:
            case R.id.btnChu:
            //在点击了+-*/时给 str_display 的 append 属性来向字符串后面添加数字或小数点，这样整个算式就会被 str_display 记录下来
            //在+-*/前后加空格是为了在计算方法中把数字和符号分割开
                str_display.append(&quot; &quot;+((Button)v).getText().toString()+&quot; &quot;);
                Results.setText(str_display);
                break;

            case R.id.btnResults:
            //点击等于按钮时在上面的文本中显示算式和答案，并且清空下面文本
                try {
                    Results.setText(str_display.toString()+&quot;=&quot;+calculate(str_display.toString()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                str_display = new StringBuffer(&quot;&quot;);
                viewResults.setText(&quot;0&quot;);
                break;

            case R.id.btnClear:
                //点击清空按钮时清空下方文本框以及储存算式的 str_display
                str_display = new StringBuffer(&quot;&quot;);
                viewResults.setText(&quot;0&quot;);
                break;
          
            case R.id.btnBackspace:
            //点击退格按钮时删除 str_display 的最后一位用 deleteCharAt()方法
                str_display.deleteCharAt(str_display.length()-1);
                Results.setText(str_display);
                try {
                    viewResults.setText(&quot;=&quot;+calculate(str_display.toString()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }

//这个计算方法用了栈的原理，不是特别难，对比着画一下图就懂了
    public String calculate(String input1) throws Exception{
        String[] comput = input1.split(&quot; &quot;);
        Stack&lt;Double&gt; stack = new Stack&lt;&gt;();
        Double m = Double.parseDouble(comput[0]);
        stack.push(m);                                      //第一个操作数入栈

        for(int i = 1; i &lt; comput.length; i++) {
            if(i%2==1) {
                if(comput[i].equals(&quot;+&quot;))
                    stack.push(Double.parseDouble(comput[i+1]));
                if(comput[i].equals(&quot;-&quot;))
                    stack.push(-Double.parseDouble(comput[i+1]));
                if(comput[i].equals(&quot;×&quot;)) {                 //将前一个数出栈做乘法再入栈
                    Double d = stack.peek();                //取栈顶元素
                    stack.pop();
                    stack.push(d*Double.parseDouble(comput[i+1]));
                }
                if(comput[i].equals(&quot;÷&quot;)) {                 //将前一个数出栈做乘法再入栈
                    double help = Double.parseDouble(comput[i+1]);
                    if(help == 0)
                        Toast.makeText(getApplicationContext(), &quot;除数不能为 0&quot;, Toast.LENGTH_SHORT).show();//不会继续执行该函数
                    double d = stack.peek();
                    stack.pop();
                    stack.push(d/help);
                }
            }
        }

        double d = 0d;

        while(!stack.isEmpty()) {           //求和
            d += stack.peek();
            stack.pop();   //出栈
        }

        String result = String.valueOf(d);
        return result;
    }
}
</code></pre>
<blockquote>
<p>🚗是不是很简单呐，下一篇见。</p>
</blockquote>

                </div>
            </article>
        </div>

        
            <div class="next-post">
                <div class="next gt-c-content-color-first">下一篇</div>
                <a href="http://www.myalger.ml/jiao-ni-yong-dai-ma-xie-yi-ge-shi-shi-yi-qing-tu/" class="post-title gt-a-link">
                    教你用代码写一个实时疫情图😷
                </a>
            </div>
        

        
            <span id="/android-ji-suan-qi-an-li/" class="leancloud_visitors" data-flag-title=" Android计算器案例🤖">
                <em class="post-meta-item-text">阅读量 </em>
                <i class="leancloud-visitors-count">0</i>
            </span>
        

        

        
            <script src='https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js'></script>

<style>
	div#vcomments{
		width:100%;
		max-width: 1000px;
		padding: 2.5%
	}
</style>


	<div id="vcomments"></div>

<script>
	new Valine({
		el: '#vcomments',
		appId: 'zSod8O6f9ppLFYxB5PgGNotJ-gzGzoHsz',
		appKey: 'zPFYmL2RAeARE6sTWFnHfJg7',
		avatar: 'retro',
		pageSize: 10,
		recordIp: true,
		placeholder: 'Just Go Go',
		visitor: true,
	});
</script>

        

        <div class="site-footer gt-c-content-color-first">
    <div class="slogan gt-c-content-color-first">春风得意马蹄疾,一日看尽长安花.
</div>
    <div class="social-container">
        
            
        
            
        
            
        
            
        
            
        
            
        
    </div>
    <div class="footer-info">
        Powered by <a href="https://github.com/getgridea/gridea" target="_blank">Gridea</a>
    </div>
    <div>
        Theme by <a href="https://imhanjie.com/" target="_blank">imhanjie</a>, Powered by <a
                href="https://github.com/getgridea/gridea" target="_blank">Gridea | <a href="http://www.myalger.ml/atom.xml" target="_blank">RSS</a></a>
    </div>
</div>

<script>
  hljs.initHighlightingOnLoad()
</script>

    </div>
</div>
</body>
</html>
